package com.ujson.chat.client.netty;

import com.ujson.chat.client.handler.*;
import com.ujson.chat.client.listener.ChannelCloseListener;
import com.ujson.chat.client.listener.ClientConnectionListener;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * <h3>ujson-parent</h3>
 * <p>netty客户端</p>
 *
 * @author JerryLiu  a1031757312@gmail.com
 * @version 1.0
 * @date 2021-11-23 21:38
 */
@Slf4j
@Service
public class NettyClient {
    @Value("${im.server.host:localhost}")
    private String host;

    @Value("${im.server.port:6500}")
    private int port;

    @Autowired
    private ChannelCloseListener channelCloseListener;
    @Autowired
    private ClientConnectionListener connectionListener;

    @Autowired
    private ClientChannelInitializer clientChannelInitializer;

    private EventLoopGroup eventLoopGroup;
    private Bootstrap bootstrap;
    private Channel channel;

    public void doConnection() {

        connectionListener.setNettyClient(this);
        eventLoopGroup = new NioEventLoopGroup();
        bootstrap = new Bootstrap();
        this.channel = bootstrap.group(eventLoopGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 1024)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(clientChannelInitializer)
                .connect(host, port)
                .addListener(connectionListener)
                .channel();
        this.channel.closeFuture().addListener(channelCloseListener);
    }

    public void destroy() {
        try {
            channel.close();
        } finally {
            eventLoopGroup.shutdownGracefully();
        }
    }

}
